package main.java.com.example.mainstream.database;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.shopapp.bean.CircleEntity;
import com.example.shopapp.dao.CircleEntityDao;

import java.util.ArrayList;
import java.util.List;


/**
 * @authors: 唐辉
 * @date: 2022/9/13
 * @description:
 **/
public class CircleDbUtils {
    public static final String DB_NAME = "circle_dbname";

    public static final int VERSION = 1;

    private static CircleDbUtils sqliteDB;

    private SQLiteDatabase db;

    private CircleDbUtils(Context context) {

    }
    /**
     * 单例模式
     * @param context
     */
    public synchronized static CircleDbUtils getInstance(Context context) {
        if (sqliteDB == null) {
            sqliteDB = new CircleDbUtils(context);
        }
        return sqliteDB;
    }
    //删除
    public void delete(Context context,long id) {

        CircleEntityDao circleEntityDao = GreenDaoManager.getmInstance().getDaoSession().getCircleEntityDao();
        circleEntityDao.deleteByKeyInTx(id);
    }
    public void update(Context context, CircleEntity comment) {
        CircleEntityDao circleEntityDao = GreenDaoManager.getmInstance().getDaoSession().getCircleEntityDao();
        circleEntityDao.update(comment);
    }
    public int insert(CircleEntity circleEntity) {
        circleEntity.setId(System.currentTimeMillis());
        CircleEntityDao circleEntityDao = GreenDaoManager.getmInstance().getDaoSession().getCircleEntityDao();
        circleEntityDao.insert(circleEntity);
        return 0;
    }
    @SuppressLint("Range")
    public List<String> findDiaryListByCircleId(String circle_id){
        List<String> diaryList = new ArrayList<>();
        CircleEntityDao circleEntityDao = GreenDaoManager.getmInstance().getDaoSession().getCircleEntityDao();
        List<CircleEntity> circleEntityList = circleEntityDao.loadAll();
        if (circleEntityList ==null || circleEntityList.size() == 0){
            return diaryList;
        }
        for (int i = 0; i < circleEntityList.size(); i++) {
            if (circle_id.equals(circleEntityList.get(i).getCircle_id())){
                diaryList.add(circleEntityList.get(i).getPath());
            }
        }
        return diaryList;
    }
    @SuppressLint("Range")
    public String findDiaryListByCircleID(String circle_id){
        Cursor cursor = db
                .query("Circle", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                if(circle_id.equals(cursor.getString(cursor.getColumnIndex("path")))){
                    return cursor.getString(cursor.getColumnIndex("circle_id"));
                }
            } while (cursor.moveToNext());
        }
        return "";
    }

}
